﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UCore;

namespace Twin {
    public partial class Merge : TConsole {

        private TConsole tc;    

        // 静态方法，负责将参数传递给实例方法
        public static void StartProcParse(object obj) {
            if (obj is TConsole tconsole) {
                // 创建 Merge 实例并调用实例方法
                Merge merge = new Merge();
                merge.procParse(tconsole);
            }
        }


        public void procParse(TConsole tconsole) {
            this.tc = tconsole;

            try {
                while (true) {
                    MsgQueue.WaitForMessage(); // 等待消息

                    while (MsgQueue.TryGetMessage(out string msg)) {
                        MergeMsg(msg);
                    }
                }
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }


        //建立Area步骤：
        //  1、读取vFROOT/mFROOT;
        //  2、读取LstArea;
        //  3、根据LstArea，按Id操作其他Area
        public static void MergeMsg(string sMsg) {
            //string sName;
            string sArea;

            //bool fCascade = _func.IsCascade(sMsg);
            int fCascade = m_dll.doIsCascade(sMsg);

            //组合segs
            if (fCascade == 1) {
                string jSeg = m_dll.Parse("G_PROFILE", sMsg);

                _Base.INFO_SEG segParsed = null;
                try {
                    segParsed = JsonConvert.DeserializeObject<_Base.INFO_SEG>(jSeg);
                } catch (Exception e) {
                    Console.WriteLine($"Error: {e.Message}");
                }

                //txtExplicit.Text += sMsg;
                //if (txtExplicit.Text.Length > 2 * 1024) txtExplicit.Text = txtExplicit.Text.Substring(1024);

                //doMerge
                string sRet = Parsing.SegsMerge(segParsed);
                if (sRet == null) {
                    return; // Merge not completed, wait for subsequent messages
                }

                //file ready !
                string kName = Parsing.convertToFullName(segParsed._FileId);
                if (kName == null) {
                    Console.WriteLine("key == null, discard !");
                    return;
                }


                sArea = sRet;
                bool f = m_dll.doCheckPack(sArea);
                if (f) {
                    Parsing.fileMap.TryAdd(kName, sArea);
                    Parsing.save_AreasIni();
                    //
                    string jArea = Parsing.postAreaGotton(kName.Substring(2));
                    styleJson(jArea, tc.txtExplicit);
                } else {
                    Console.WriteLine("Check pack false, sArea={1}", sArea);
                }
            }

            //单Msg
            else {
                string jMsg = m_dll.Parse("G_INFO", sMsg);
                _Base.INFO_MSG infoParsed = JsonConvert.DeserializeObject<_Base.INFO_MSG>(jMsg);

                //u-msg skip
                if (infoParsed._bInstDir == "1") return;

                //只显示响应
                if (tc.optProfile.Checked) {
                    jMsg = m_dll.Parse("G_PROFILE", sMsg);
                } else if (optInstant.Checked) {
                    jMsg = m_dll.Parse("G_INSTANT", sMsg);
                } else if (optDetail.Checked) {
                    jMsg = m_dll.Parse("G_DETAIL", sMsg);
                }

                styleJson(jMsg, tc.txtExplicit);
            }
        }



        //在textbox显示styled json
        public void styleJson(string json, TextBox txtbox) {
            // 格式化JSON字符串
            dynamic parsedJson = JsonConvert.DeserializeObject(json);
            string formattedJson = JsonConvert.SerializeObject(parsedJson, Formatting.Indented);

            Action updateTextbox = () => {
                txtbox.Text = formattedJson;
            };

            // 在 UI 线程上执行更新操作
            if (txtbox.InvokeRequired) {
                txtbox.BeginInvoke(updateTextbox);
            } else {
                //updateTextbox();
                txtbox.Text = formattedJson;
            }
        }


    }
}
